/**
 * 静态方法
 * Name = poolManager
 * DateTime = Sun Jan 16 2022 00:47:17 GMT+0800 (中国标准时间)
 * Author = Created by zhj9922
 * FileBasename = poolManager.ts
 * gitee： https://gitee.com/coyeking
 */
 import { _decorator, Prefab, Node, instantiate, NodePool } from "cc";
 const { ccclass, property } = _decorator;
 
 @ccclass("poolManager")
 export class poolManager {
 
     dictPool: any = {}
     dictPrefab: any = {}
 
     static _instance: poolManager;
 
     static get instance () {
         if (this._instance) {
             return this._instance;
         }
 
         this._instance = new poolManager();
         return this._instance;
     }
 
     /**
      * 根据预设从对象池中获取对应节点
      */
     getNode (prefab: Prefab, parent: Node) {
         let name = prefab.name;
          //@ts-ignore
          if (!prefab.position) {
             //@ts-ignore
             name = prefab.data.name;
         }
         
         this.dictPrefab[name] = prefab;
         let node = null;
         if (this.dictPool.hasOwnProperty(name)) {
             //已有对应的对象池
             let pool = this.dictPool[name];
             if (pool.size() > 0) {
                 node = pool.get();
             } else {
                 node = instantiate(prefab);
             }
         } else {
             //没有对应对象池，创建他！
             let pool = new NodePool();
             this.dictPool[name] = pool;
 
             node = instantiate(prefab);
         }
         if (parent){
            node.parent = parent;
         }
         
         node.active = true;
         return node;
     }
 
     /**
      * 将对应节点放回对象池中
      */
     putNode (node: Node) {
         if (!node) {
             return;
         }
         let name = node.name; 
         let pool = null;
         if (this.dictPool.hasOwnProperty(name)) {
             //已有对应的对象池
             pool = this.dictPool[name];
         } else {
             //没有对应对象池，创建他！
             pool = new NodePool();
             this.dictPool[name] = pool;
         }
 
         pool.put(node);
     }
 
     /**
      * 根据名称，清除对应对象池
      */
     clearPool (name: string) {
         if (this.dictPool.hasOwnProperty(name)) {
             let pool = this.dictPool[name];
             pool.clear();
         }
     }
 }
 